package com.ita.servlet.menu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.AbstractDocument.BranchElement;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.ita.factory.MServiceFactory;
import com.ita.pojo.Menu;
import com.ita.pojo.Merchant;
import com.ita.service.MenuService;
import com.ita.util.Constant;
import com.ita.util.FileUtil;
import com.ita.util.JsonUtil;
import com.ita.util.PropertiesUtil;
import com.ita.vo.JsonResult;

@WebServlet("/sec/menu/fmodify")
public class FModifyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MenuService manager = null;
	private Logger logger = Logger.getLogger(AddServlet.class);
	private Properties properties;
	private ServletFileUpload upload;

	public FModifyServlet() {
		super();
		properties = PropertiesUtil.getProp();
		manager = MServiceFactory.getMenuService();
		DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
				new File("/temp"));
		upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		String menuPath = properties.getProperty("FOOD_PATH");
		String pathName = null;
		String server_path = "http://"
				+ InetAddress.getLocalHost().getHostAddress() + ":" + "9000/";

		String id = (String) request.getSession().getAttribute("update_id");
		String mid = ((Merchant) request.getSession().getAttribute("m"))
				.getId();
		String name = null;
		String cprice = null;
		String image = null;
		String type = null;

		List<FileItem> items = null;

		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			logger.error(e.getMessage());
		}

		for (FileItem item : items) {
			if (item.isFormField()) {
				String value = item.getString("utf-8");

				switch (item.getFieldName()) {
				case "id":
//					id = value;
					break;
				case "name":
					name = value;
					break;
				case "price":
					cprice = value;
					break;
				case "type":
					type = value;
					break;
				default:
					break;
				}

			} else {
				InputStream in = item.getInputStream();
				System.out.println(item.getName() + "..." + item.getSize());
				String image_type = item
						.getName()
						.subSequence(item.getName().lastIndexOf("."),
								item.getName().length()).toString();
				if (".jpg".equals(image_type) || ".gif".equals(image_type)
						|| ".jpeg".equals(image_type)
						|| ".png".equals(image_type)) {
					byte[] bytes = new byte[in.available()];
					in.read(bytes);
					pathName = menuPath +id + image_type;
					image = server_path + "/food/"+id+ image_type;
					FileUtil.writeFile(pathName, bytes);
				} else {
					JsonResult jsonResult = new JsonResult();
					String info = "Format of img wrong!";
					jsonResult.setCode(Constant.FAIL_CODE);
					jsonResult.setMsg(info);
					String json = JsonUtil.getJsonFromObject(jsonResult);
					PrintWriter out = response.getWriter();
					out.write(json);
					out.flush();
					out.close();
					return;
				}
			}
		}

		Double price = Double.parseDouble(cprice);

		Menu menu = new Menu();
		menu.setId(id);
		menu.setName(name);
		menu.setPrice(price);
		menu.setType(type);
		menu.setImg(image);
		menu.setMid(mid);

		int m = manager.updateMenu(menu);

		JsonResult jsonResult = new JsonResult();
		String info = "";
		if (m > 0) {
			jsonResult.setCode(Constant.SUCEESS_CODE);
			info = "Modify Success!";
		} else {
			jsonResult.setCode(Constant.FAIL_CODE);
			info = "Modify Fail!";
		}

		jsonResult.setMsg(info);
		String json = JsonUtil.getJsonFromObject(jsonResult);

		PrintWriter out = response.getWriter();
		out.write(json);
		out.flush();
		out.close();

	}

}
